﻿using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using NTTDATA.BEENChina.ResultCertification.DataStore;
using NTTDATA.BEENChina.ResultCertification.EntryModel;
using NTTDATA.BEENChina.ResultCertification.Result;
using NTTDATA.BEENChina.ResultCertification.Util;

namespace NTTDATA.BEENChina.ResultCertification.Logic
{
    public class VerfityJob
    {
        private const int ImagePackage = 10;

        private IMakeJob _makeJob;

        public VerfityJob()
        {
            _makeJob = new MakeJobClientAccess();
        }

        /// <summary>
        /// 做job
        /// </summary>
        /// <param name="oridReceiveDate"></param>
        public void MakeJob(string oridReceiveDate)
        {
            var threadMakeJob = new Thread(() =>
                    {
                //get all verfityItem
                List<string> verfityItemIds = _makeJob.GetDistinctVerfityItemIds(oridReceiveDate);

                if (verfityItemIds != null)
                {
                    ActionMessage.GetInstance().onProcessMessage("做成Job 开始", EnumProcessModel.做成检查Job);

                    int itemCount = verfityItemIds.Count;

                    foreach (var verfityItemId in verfityItemIds)
                    {                    
                        //List<string> childSeqnos = _makeJob.GetChildImageSeqnos(oridReceiveDate, verfityItemId);
                        List<ChildImage> childSeqnos = _makeJob.GetChildImageSeqnos(oridReceiveDate, verfityItemId);

                        IEnumerable<List<ChildImage>> result = SplitCollections(childSeqnos);

                        int resultCount = result.Count();

                        foreach (var splitResult in result)
                        {
                            resultCount--;

                            string guid = System.Guid.NewGuid().ToString();

                            ActionMessage.GetInstance().onProcessMessage(string.Format("检验项目 {0} 做成中,剩余 {1} .", verfityItemId, resultCount), EnumProcessModel.做成检查Job);

                            //make a verfityjob
                            _makeJob.MakeVerfityJob(guid, verfityItemId, oridReceiveDate, splitResult.Count,
                                                    splitResult.First().CategoryId, splitResult.First().CategoryName
                                );

                            //update child image object verfityjobid
                            _makeJob.UpdateChildImageVerfityJobId(guid, splitResult.Select(o=>o.ImageId).ToList());
                        }

                        itemCount--;
                        ActionMessage.GetInstance().onProcessMessage(string.Format("剩余 检验项目 {0}",itemCount), EnumProcessModel.做成检查Job);

                    }


                    ActionMessage.GetInstance().onProcessMessage("做成Job 结束", EnumProcessModel.做成检查Job);


                }
                    }) { Name = "MakeJob" };

            threadMakeJob.Start();  
        }

        ///// <summary>
        ///// 按照固定大小 拆分image
        ///// </summary>
        ///// <param name="childSeqnos"></param>
        ///// <returns></returns>
        //private IEnumerable<List<string>> SplitCollections(List<string> childSeqnos )
        //{   
        //    List<List<string>> result = new List<List<string>>();

        //    if (childSeqnos != null)
        //    {
        //        int iCount = childSeqnos.Count;

        //        for (int i = 0; i < iCount;)
        //        {
        //            if (i + ImagePackage > iCount)
        //            {
        //                result.Add(childSeqnos.GetRange(i , iCount - i));
        //            }
        //            else
        //            {
        //                result.Add(childSeqnos.GetRange(i, ImagePackage));                    
        //            }

        //            i += ImagePackage;
        //        }
        //    }
        //    return result;
        //}

        /// <summary>
        /// 按照固定大小 拆分image
        /// </summary>
        /// <param name="childSeqnos"></param>
        /// <returns></returns>
        private IEnumerable<List<ChildImage>> SplitCollections(List<ChildImage> childSeqnos)
        {
            List<List<ChildImage>> result = new List<List<ChildImage>>();

            if (childSeqnos == null)
            {
                return result ;
            }

            IEnumerable<string> categoryList = childSeqnos.Select(o => o.CategoryId).Distinct();
            foreach (string categoryId in categoryList)
            {
                List<ChildImage> childImageList = childSeqnos.Where(o => o.CategoryId == categoryId).ToList();
                
                List<List<ChildImage>> splitedList = splitChildImageList(childImageList);
                if (splitedList == null || splitedList.Count <= 0)
                {
                    continue;
                }

                result.AddRange(splitedList);
            }            
            return result;
        }

        private List<List<ChildImage>> splitChildImageList(List<ChildImage> childImageList)
        {
            if (childImageList == null)
            {
                return null;
            }

            List<List<ChildImage>> result = new List<List<ChildImage>>();

            int iCount = childImageList.Count();
            for (int i = 0; i < iCount; i += ImagePackage)
            {
                if (i + ImagePackage > iCount)
                {
                    result.Add(childImageList.GetRange(i, iCount - i) );
                }
                else
                {
                    result.Add(childImageList.GetRange(i, ImagePackage) );                    
                }                
            }        
            return result;
        }

/*        /// <summary>
        /// 补全opid
        /// </summary>
        public void CompleteOpId()
        {
            var threadCompleteOpId = new Thread(() =>
                    {
                        ActionMessage.GetInstance().onProcessMessage("补全OPID开始",
                                                                        EnumProcessModel.补全opid);
                        EntryClientAccess access = new EntryClientAccess();
                        List<ChildImage> ngImageList = access.GetNgChildImageObjects();
                        if (ngImageList != null)
                        {
                            ActionMessage.GetInstance().onProcessMessage(
                                "补全OPID,ChildImag Count: " + ngImageList.Count(),
                                EnumProcessModel.补全opid);
                            int i = 0;
                            DataSource datasource = new DataSource();
                            DataTarget dataTarget = new DataTarget();
                            foreach (ChildImage image in ngImageList)
                            {
                                ChildImage newChildImage = datasource.CompleteOpId(image);

                                //只保存OPId
                                dataTarget.UpdateChildImageOpId(image);

                                ActionMessage.GetInstance().onProcessMessage(
                                    "补全OPID,NO. : " +
                                    i++.ToString(CultureInfo.InvariantCulture) + "ImageID: " +
                                    newChildImage.ImageId, EnumProcessModel.补全opid);
                            }
                        }
                        ActionMessage.GetInstance().onProcessMessage("补全OPID结束",
                                                                        EnumProcessModel.补全opid);
                    }) { Name = "CompleteOpId"  };

            threadCompleteOpId.Start();  
        }*/

        /// <summary>
        /// 补全opid
        /// 补全image
        /// </summary>
        public void CompleteOpIdAndImage()
        {
            var threadCompleteOpId = new Thread(() =>
            {
                ActionMessage.GetInstance().onProcessMessage("补全OPID,Image开始",
                                                                EnumProcessModel.补全opid);
                EntryClientAccess access = new EntryClientAccess();
                List<ChildImage> ngImageList = access.GetNgChildImageObjects();
                if (ngImageList != null)
                {
                    ActionMessage.GetInstance().onProcessMessage(
                        "补全OPID,ChildImag Count: " + ngImageList.Count(),
                        EnumProcessModel.补全opid);
                    int i = 0;

                    //定义局部变量
                    var datasource = new DataSource();
                    var dataTarget = new DataTarget();
                    var imageDownLoadHelper = new Util.ImageDownloadHelper();

                    foreach (ChildImage image in ngImageList)
                    {
                        // ChildImage newChildImage = datasource.CompleteOpId(image);

                        CompleteOpIdAndImage(image);

                       
                        //更新
                        ActionMessage.GetInstance().onProcessMessage(
                            "补全OPID,Image,NO. : " +
                            i++.ToString(CultureInfo.InvariantCulture) + "ImageID: " +
                            image.ImageId, EnumProcessModel.补全opid);
                    }
                }
                ActionMessage.GetInstance().onProcessMessage("补全OPID,Image结束",
                                                                EnumProcessModel.补全opid);
            }) { Name = "CompleteOpId" };

            threadCompleteOpId.Start();
        }

        /// <summary>
        /// 上传job
        /// </summary>
        /// <param name="opid"></param>
        /// <param name="verfityJobItem"></param>
        /// <returns></returns>
        public int UpLoadJob(string opid, VerfityJobItem verfityJobItem)
        {
            IEntryClient entryClient = new EntryClientAccess();

            //找到画像
            //保存画像和结果
            FindResultAndConvertImage(verfityJobItem);

            //更新job
            int effactRow= entryClient.UpLoadJob(opid, verfityJobItem);

            return effactRow;

        }

        private void FindResultAndConvertImage(VerfityJobItem verfityJobItem)
        { 

            foreach (var childImage in verfityJobItem.ChildImage)
            {
                CompleteOpIdAndImage(childImage);
            }
        }

        private static void CompleteOpIdAndImage(ChildImage childImage)
        {
            var datasource = new DataSource();
            var dataTarget = new DataTarget();
            var imageDownLoadHelper = new ImageDownloadHelper();


            childImage = datasource.CompleteOpId(childImage); 

            //错误的留取画像  
            if (childImage.VerfityConfirmResult.Result.Equals("2"))
            {
                if (childImage.ImageData != null)
                {
                    //补全imagedata
                    childImage.Reason.PngImageData = new ImageConvert().ConvertToPngBase64(childImage.ImageData);
                }
                else
                {
                    imageDownLoadHelper.GetImageData(childImage);

                    if (childImage.ImageData != null)
                    {
                        childImage.Reason.PngImageData = new ImageConvert().ConvertToPngBase64(childImage.ImageData);
                    }
                }
            }

            //补全opid
                var threadCompleteOpIdAndImage = new Thread(() =>
                        dataTarget.SaveVerfityConfirmResultAndOpid(childImage))
                        { Name = "CompleteOpIdAndImage" };
                threadCompleteOpIdAndImage.Start();
            }
         
    }
}
